package com.aSemy.qotwReader.core.question;

import java.io.*;

import com.aSemy.qotwReader.core.CmdOptions;
import com.aSemy.qotwReader.core.types.EbookType;
import com.aSemy.qotwReader.core.utils.*;



/**
 * Details regarding converting the question to an ebook with all the metadata, and a good file name and path name.
 * @author Adam Semenenko
 */
public class QuestionEbook
{
    /** The file where the HTML is saved. */
    final private File savedHTMLFile;
    /** Metadata about the question (title, date, etc). */
    final private QuestionData data;
    /** Commands to convert the book, including the correct metadata. */
    final private CmdOptions cmdOpts;
    
    /**
     * Creates an ebook 
     * @param savedHTMLFile The object containing the information about the saved HTML code of the question
     * @param data Information parsed from the question (title, date, etc).
     */
    public QuestionEbook(QuestionFile savedHTMLFile, QuestionData data)
    {
        this.savedHTMLFile = savedHTMLFile.getOutputFile();
        this.data = data;
        this.cmdOpts = new CmdOptions(data);
    }
    
    /**
     * Converts the HTML to an ebook.
     * @param outputEbook The type of ebook to convert to.
     * @param directoryOfCalibreEbookConverter Where Calibre is installed.
     */
    public void convertToFormat(EbookType outputEbook, File directoryOfCalibreEbookConverter)
    {
        //ebook-convert input_file output_file [options]
        try
        {
            Runtime rt = Runtime.getRuntime();

            String filename = Filenames.getFilename(outputEbook, data);
            
            File saveFile = new File(filename);
            
            if (saveFile.getParentFile() != null)
                saveFile.getParentFile().mkdirs();
            
            String cmd = 
                " ebook-convert "
                + "\"" + savedHTMLFile.getAbsoluteFile() + "\" "
                + "\"" + saveFile.getAbsoluteFile() + "\""
                + cmdOpts.getOptionsForConversion();
            
            System.out.println("cmd: " + cmd);
            
            Process cd = rt.exec(cmd, null, directoryOfCalibreEbookConverter);//
            
            
            BufferedReader input = new BufferedReader(new InputStreamReader(cd.getInputStream()));
            
            String line = null;
            
            while((line = input.readLine()) != null)
                System.out.println(line);

            System.out.println("Exited with error code " + cd.waitFor());
    
        } catch(Exception e)
        {
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
}
